package caom.wangs.java8.streamDemo;

import caom.wangs.java8.pojo.Apple;

import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import static caom.wangs.java8.streamDemo.DataServer.appleStore;


/**
 * stream 流行原因：加载不同服务的 db 中的数据 拿到内存中去加工。（解决多数据源的问题）
 */
public class Demo1 {
    public static void main(String[] args) {

        appleStore.stream().filter(apple -> apple.getColor().equals("red"))
//                .sorted()
                .distinct()
                .map(apple -> apple.getColor()).forEach(System.out::println);


        // 获取红色苹果的总重量
        // select sum(a.weight) from apple as a where a.color='red';
        double red = appleStore.stream().filter(apple -> apple.getColor().equals("red"))
                .mapToDouble(Apple::getWeight).sum();
        System.out.println(red);

        //by 颜色统计平均重量
        // select a.color,sum(a.weight) from apple a group by a.color;
        Collector<Apple, ?, Map<String, Double>> groupConllector =
                Collectors.groupingBy(Apple::getColor, Collectors.averagingDouble(Apple::getWeight));
        Map<String, Double> collect = appleStore.stream().collect(groupConllector);
        collect.forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });

    }
}
